package com.jh.paymentchannel.service;

import cn.jh.common.utils.CommonConstants;
import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.pojo.MiLianQuickRegister;
import com.jh.paymentchannel.util.Util;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

@Service
public class MiLianQuickTopupRequest implements RepaymentRequest{
    private static final Logger log = LoggerFactory.getLogger(MiLianQuickTopupRequest.class);

    @Value("${payment.ipAddress}")
    private String ipAddress;

    @Autowired
    private TopupPayChannelBusiness topupPayChannelBusiness;

    @Autowired
    private Util util;

    @Autowired
    private BranchbankBussiness branchbankBussiness;

    @Autowired
    MilianQuickpageRequest milianQuickpageRequest;

    @Autowired
    MiLianQuickService miLianQuickService;

    @Override
    public Map<String, String> topupRequest(HttpServletRequest request, String amount, String ordercode,
                                            String orderdesc, String extra, String notifyurl, String returnurl, String channelParam) throws Exception {

        log.info("调用米联 MilianQuick 通道开始");
        Map<String, String> map = new HashMap<String, String>();
        RestTemplate restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("transactionclear", "error url request!");
        String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("order_code", ordercode);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        log.info("查询订单信息结果result={}" + result);
        JSONObject jsonObject;
        JSONObject resultObj;
        try {
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
        } catch (Exception e) {
            log.error("查询订单信息出错");
            map.put("resp_code", "failed");
            map.put("channel_type", "milian_quick");
            map.put("resp_message", "没有该订单信息");
            return map;
        }
        String userid = resultObj.getString("userid");
        // 费率
        String rate = resultObj.getString("rate");
        // 额外费率
        String extraFee = resultObj.getString("extraFee");
        //代付费
        String costFee = resultObj.getString("costfee");
        // 信用卡
        String bankCard = resultObj.getString("bankcard");

        String orderType = resultObj.getString("type");

        String realAmount = resultObj.getString("realAmount");
        String orderChannleTag = resultObj.getString("channelTag");
        String brandId = resultObj.getString("brandid");

        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/bank/default/cardno";
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("cardno", bankCard);
        requestEntity.add("type", "0");
        result = restTemplate.postForObject(url, requestEntity, String.class);
        log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
        try {
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
        } catch (Exception e) {
            log.error("查询银行卡信息出错");
            map.put("resp_code", "failed");
            map.put("channel_type", "milian_quick");
            map.put("resp_message", "查询银行卡信息有误");
            return map;
        }
        String mobile = resultObj.getString("phone"); // 预留信用卡手机号码
        String idcard = resultObj.getString("idcard");// 身份证号
        String userName = resultObj.getString("userName");// 用户姓名
        String bankName = resultObj.getString("bankName");
        String expiredTime = resultObj.getString("expiredTime");
        String securityCode = resultObj.getString("securityCode");
        String nature = resultObj.getString("nature");

        MiLianQuickRegister miLianQuickRegister = topupPayChannelBusiness.getMiLianQuickRegister(Long.valueOf(userid),bankCard);
        log.info("查询米联进件信息miLianQuickRegister={}",miLianQuickRegister);
        if (miLianQuickRegister == null) {
            /*在绑卡之后会立即进件，所以理论上这一步不会出现miLianQuickRegister为空的情况*/
            log.info("---- MilianQuick 发起支付，查询米联进件信息异常. 找不到记录 --");
            map.put(CommonConstants.RESP_CODE, "failed");
            map.put("channel_type", "milian_quick");
            map.put(CommonConstants.RESP_MESSAGE, "查询米联进件信息异常");
            return map;
        }

        log.info("----- MilianQuick topupRequest processing----");
        if(miLianQuickRegister.getState() != null && miLianQuickRegister.getState().equals("N")){
            log.info("---- MilianQuick 发起支付，米联进件成功但是未绑卡或绑卡失败 --");
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put("channel_type", "milian_quick");
            map.put(CommonConstants.RESP_MESSAGE, "米联进件成功但是未绑卡或绑卡失败");
            return map;
        }

        log.info(" --------------- 米联quick发起交易复查进件和绑卡信息 -----------------");
        Map<String, String> resultReg = miLianQuickService.mlQuickReister(userid, bankCard, orderChannleTag,brandId);
        if(!CommonConstants.SUCCESS.equals(resultReg.get(CommonConstants.RESP_CODE))){
            log.info("---- MilianQuick 发起支付，检查进件信息出错");
            return resultReg;
        }
        if("8".equals(orderType)) {
            log.info("根据判断进入消费任务===进入米联quick mlQuickPay===");

            map  = (Map<String, String>) milianQuickpageRequest.mlQuickPay(ordercode, securityCode, expiredTime,miLianQuickRegister);

        }else {
            log.info("根据判断进入还款任务 == 进入米联quick mlQuickDF == ");
            map = (Map) milianQuickpageRequest.mlQuickDF(ordercode,miLianQuickRegister);
        }
        return map;

//        /*判断是否有进件;判断进件时的费率和代付费是否和当前一致,不一致需要修改商户进件*/
//        /*考虑在进行定时代扣不存在用户还没有进件，首笔交易到此时应该以及进件完成，所以不做进件信息为空判断，此处只存在修改进件的操作*/
//        if (!miLianQuickRegister.getDebitRate().equals(rate)
//                && !miLianQuickRegister.getCountFee().equals(costFee)
//                //信用卡不一样应该在进件表里面存在同一用户多条数据,但是同一用户和信用卡只有一条数据
//                /*&& !miLianQuickRegister.getBankCard().equals(bankCard)*/) {
//
//            /*修改进件信息*/
//            Map mLQuickRegister = (Map<String, String>) milianQuickpageRequest.register(request,ordercode,"M");
//            /*判断进件是否成功，成功则开始交易和代扣*/
//            if (CommonConstants.SUCCESS.equals(mLQuickRegister.get(CommonConstants.RESP_CODE))) {
//                log.info("米联用户修改进件成功==========");
//                if("8".equals(orderType)) {
//                    log.info("根据判断进入消费任务======");
//
//                    map  = (Map<String, String>) milianQuickpageRequest.mlQuickPay(ordercode, securityCode, expiredTime,miLianQuickRegister);
//
//                }else {
//                    log.info("根据判断进入还款任务");
//
//                    map = (Map) milianQuickpageRequest.mlQuickDF(ordercode,miLianQuickRegister);
//
//                }
//                return map;
//            }else {
//                log.info("用户修改进件失败====== ordercode:" + ordercode);
//                map.put("resp_code", "failed");
//                map.put("channel_type", "milian");
//                map.put("resp_message", (String) mLQuickRegister.get(CommonConstants.RESP_MESSAGE));
//                return map;
//            }
//
//        }else{
//            if("8".equals(orderType)) {
//                log.info("根据判断进入消费任务======");
//
//                map  = (Map<String, String>) milianQuickpageRequest.mlQuickPay(ordercode, securityCode, expiredTime,miLianQuickRegister);
//
//            }else {
//                log.info("根据判断进入还款任务");
//                map = (Map) milianQuickpageRequest.mlQuickDF(ordercode,miLianQuickRegister);
//            }
//            return map;
//        }
    }

    @Override
    public  Map<String, String> verifyBindCardRequest(HttpServletRequest request,String channelTag, String userId,
                                                      String creditCardNumber, String brandId) throws Exception{
        log.info("==绑卡 MilianQuick verifyBindCardRequest == ");
        Map<String, String> map = new HashMap<String, String>();

        try {
            Map<String, String> resultReg = miLianQuickService.mlQuickReister(userId, creditCardNumber, channelTag,brandId);
            if(!CommonConstants.SUCCESS.equals(resultReg.get(CommonConstants.RESP_CODE))){
                return resultReg;
            }
            log.info("== 开始绑卡 MilianQuick verifyBindCardRequest == ");
            map = miLianQuickService.miLianBindBankCard(userId, creditCardNumber, brandId);
        }catch (Exception e){
            log.info(" == 米联miLianBankCard 出错. " + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.网络出错了哦,臣妾已经尽力了,请重试~");
            return map;
        }

        // 如果已经绑定过 返回 map.put(CommonConstants.RESP_CODE, CommonConstants.STATUS_VALID);
        return map;
    }

}
